<?php
namespace app\admin\classes;

use core\Api;
use core\V;
use core\Res;
use core\Func;


/**
 * 基础审核类
 */
class BasicVerify extends \C {

  static $model;
  // 本页地址
  static $hash="";
  // 展开的菜单
  static $menuHash="";

  static $status_new="1";
  static $status_pass="2";
  static $status_fail="3";
  static $verify_msg_col="remark";

  static $title=[
    "show"=>true,
    "title"=>"",
    "breadcrumb"=>[],
    "subtitle"=>"",
    "panel"=>"",
  ];
  // 配置选项
  static $conf=[
    // 文本模板配置
    "tpl"=>"",
    // 视图文件配置
    "view"=>""
  ];



  protected function btn($conf,$width="100px"){
    $btn="";
    if (!empty($conf)){
      $btn='
      <el-table-column
        fixed="right"
        label="操作"
        align="right"
        header-align="right"
        width="'.$width.'">
        <template slot-scope="scope">
      ';
      foreach ($conf as $v) {
        if (empty($v["name"])) continue;
        $name=$v["name"];
        $class=(empty($v["class"]))?"":$v["class"];
        $onclick=(empty($v["onclick"]))?"":'@click="'.$v["onclick"].'(scope.row)"';
        $b='<el-button class="result-btn '.$class.'" '.$onclick.' type="text" size="small">'.$name.'</el-button>';
        $btn.=$b;
      }

      $btn.='
        </template>
      </el-table-column>
      ';
    }

    $this->VD([
      "___btn___"=>$btn,
    ]);
  }

  public function result_body(){
    return "";
  }



  // 钩子函数
  public function queryFilter(&$query){
    $query->where("status",static::$status_new);
  }

  // 获取结果之前
  protected function before_result(&$query){
    $query->hidden(["create_at","update_at","delete_at"]);
  }
  // 获取结果之后
  protected function after_result(&$res,$list){
    return $list;
  }

  // 分页处理
  protected function set_page(&$query){
    $page=input("page","1");
    $pagesize=input("pagesize","10");
    $query->page($page,$pagesize);
  }
  // 分页处理
  protected function set_order(&$query){
    $order=input("order");
    if ((!empty($order)) && is_array($order)){
      $query->order($order);
    }else{
      $query->order(["id"=>"desc"]);
    }
  }


  public function verify_pass(){
    $id=input("id");
    empty($id) and Api::error("请选择记录");
    $res=static::$model::where('id','in',$id)
                        ->update(['status' => static::$status_pass]);
    if ($res>0){
      Api::ok("保存成功");
    }else{
      Api::error("遇到错误");
    }
  }
  public function verify_fail(){
    $id=input("id");
    empty($id) and Api::error("请选择记录");
    $remark=input(static::$verify_msg_col);
    empty($remark) and Api::error("请输入原因");

    $res=static::$model::where('id','in',$id)
                        ->update(['status' => static::$status_fail,'remark'=>$remark]);
    if ($res>0){
      Api::ok("保存成功");
    }else{
      Api::error("遇到错误");
    }
  }

  // 首页
  public function index(){
    $conf=static::$conf;
    $conf["title"]=static::$title;
    $this->wapper([
      "show"=>$conf["title"]["show"],
      "title"=>$conf["title"]["title"],
      "breadcrumb"=>$conf["title"]["breadcrumb"],
      "panel"=>isset($conf["title"]["panel"]),
      "subtitle"=>$conf["title"]["subtitle"],
    ]);

    $this->VD([
      "apiBase"=>static::$hash,
    ]);

    $this->btn([
      [
        "name"=>"通过",
        "class"=>"",
        "onclick"=>"verify_pass_one",
      ],
      [
        "name"=>"拒绝",
        "class"=>"",
        "onclick"=>"verify_fail_one",
      ],
    ],"200px");

    if (!empty($conf["view"])){
      return view($conf["view"],$this->VD());
    }else{
      if (empty($conf["tpl"])) $conf["tpl"]=BasicSearchTemplet::index();
      return $this->displayout("index",$conf["tpl"],$this->VD());
    }


  }
  protected function get_query(){

    $query=static::$model::where(1);

    $this->queryFilter($query);
    return $query;
  }
  protected function make_list(&$query){
    $res=$query->all();
    $list=$res->toArray();
    return $list;
  }
  protected function get_list(&$query){
    $this->before_result($query);
    $list=$this->make_list($query);
    $list=$this->after_result($res,$list);
    return $list;
  }

  public function getresult(){


    if(method_exists($this,'raw_query')){
      $res=$this->raw_query();
      $total=$res["total"];
      $list=$res["list"];
    }else{
      $query=$this->get_query();

      $total=$query->count();

      $this->set_page($query);
      $this->set_order($query);

      $list=$this->get_list($query);
    }


    Api::ok([
      "total"=>$total,
      "list"=>$list,
    ]);

  }



  // 重写display方法
  protected function displayout($key,$t="",$v=[],$c=[]){

    if ($key=="index"){

      $t=str_replace("___result___",$this->result_body(),$t);
      // $t=str_replace("___search___",$this->search_body(),$t);

    }

    $t=str_replace("___vue___",$this->getVD("___vue___"),$t);
    $t=str_replace("___css___",$this->getVD("___css___"),$t);
    $t=str_replace("___btn___",$this->getVD("___btn___"),$t);
    $t=str_replace("___footerbtn___",$this->getVD("___footerbtn___"),$t);

    if (!empty(static::$menuHash)){
      $this->menuActive(static::$menuHash);
    }

    return $this->display($t,$v,$c);
  }

}

/**
 * 模板
 */
class BasicSearchTemplet
{
  static function index(){


    $html=<<<'CODE'
    {layout name="/public/layout_index" /}

    <style>
    .is-right > .cell{
      display:inline;
    }

    .hover:hover{
      color:#1e88e5 !important;
    }


    ___css___
    </style>

    <div id="app" v-cloak>

      <c-card title="查询结果" v-loading="result_loading" footer="true">
        <template slot="header-right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.currentPage"
              :page-sizes="[10, 20, 50, 100, 300, 500]"
              :page-size="page.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total">
            </el-pagination>
        </template>
        <template slot="footer-right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.currentPage"
              :page-sizes="[10, 20, 50, 100, 300, 500]"
              :page-size="page.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total">
            </el-pagination>
        </template>

        <template slot="footer">

          <el-button
            @click="verify_all(true)"
            data-toggle="tooltip"
            title="全部通过"
            class="btn-success waves-effect waves-light"
            type="info"
            icon="el-icon-check"
            style="outline: none;"
            circle>
          </el-button>
          <el-button
            @click="verify_all(false)"
            data-toggle="tooltip"
            title="全部拒绝"
            class="btn-danger waves-effect waves-light"
            type="info"
            icon="el-icon-close"
            style="outline: none;"
            circle>
          </el-button>

        </template>



            <el-table

              :data="list"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
              ___result___
              ___btn___
            </el-table>


      </c-card>


    </div>



    <script>
    var mixin = {
      ___vue___
    };
    var base_mixin={
      data:{
        apiBase:"{$apiBase}",
        result_loading:true,
        form:{},
        order:{},
        page: {
          currentPage:1,
          total: 0,
          pagesize: 10
        },
        list:[],
        multipleSelection:[]

      },
      methods: {
        init(){
          this.Search();
        },

        verify_pass_one: function(row){
          var ids=[row.id];
          this.verify_pass(ids);
        },
        verify_fail_one: function(row){
          var ids=[row.id];
          this.verify_fail(ids);
        },
        verify_all: function(pass){
          var ids=[];
          for (var v in this.multipleSelection) ids.push(this.multipleSelection[v].id)
          if (pass){
            this.verify_pass(ids);
          }else{
            this.verify_fail(ids);
          }

        },

        verify_pass: function(ids){
          var that=this;
          APP.ajax(this.apiBase+"/verify_pass",{id:ids},function(msg){
            if (msg.result){
              APP.alert(msg.data,true);
              that.Search();
            }else{
              APP.alert(msg.data);
            }
          });
        },
        verify_fail: function(ids){
          var that=this;
          this.$prompt('请输入拒绝原因', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValidator: function(value){
                      value=String(value).trim();
                      if (!value) return "请输入拒绝原因";
                    }
                  }).then(({ value }) => {
                    APP.ajax(this.apiBase+"/verify_fail",{id:ids,remark:value},function(msg){
                      if (msg.result){
                        APP.alert(msg.data,true);
                        that.Search();
                      }else{
                        APP.alert(msg.data);
                      }
                    });

                  }).catch(() => {

                  });
        },
        handleSelectionChange(val) {
          this.multipleSelection = val;
        },
        Search: function(){
          this.activeNames=[];
          this.result_show=true;
          this.result_loading=true;

          var that=this;
          var postData={
            order:this.order,
            form: this.form,
            page: this.page.currentPage,
            pagesize: this.page.pagesize
          };
          APP.ajax(this.apiBase+"/getresult",postData,function(msg){
            that.result_loading=false;
            if (msg.result){
              that.page.total=parseInt(msg.data.total);
              that.list=msg.data.list;
            }else{
              APP.alert(msg.data);
            }
          });
        },
        handleSizeChange: function(val) {
          this.page.pagesize=val;
          this.Search();
        },
        handleCurrentChange: function(val) {
          this.page.currentPage=val;
          this.Search();
        },
        goTop:function(){
          this.activeNames=["1"];
          $("html,body").animate({scrollTop:0},1000);
        }

      },
      mounted(){
        var that=this;
        this.$nextTick(function () {
          that.init();
        })
      }
    };
    var main=new Vue({
      el:"#app",
      mixins: [base_mixin,mixin],

    });

    </script>


CODE;
    return $html;

  }

}
